<template>
<div style=" height: 6vh; background-color: #fff;padding: 10px 20px">
  <span style="line-height: 60px;font-size: 20px">用户管理</span>
  <el-button type="primary" style="float: right;margin-top: 13px"
            @click="dialogVisible=true">新建用户</el-button>
</div>
<!--  新增用户弹窗-->
  <el-dialog :title="dialogTitle" style="width: 1000px;padding: 40px" v-model="dialogVisible">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
       <el-col :span="12">
         <el-form-item label="用户名">
           <el-input v-model="saveUserForm.username" placeholder="请输入用户名"></el-input>
         </el-form-item>
       </el-col>
        <el-col :span="12">
          <el-form-item label="手机号">
            <el-input v-model="saveUserForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input v-model="saveUserForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄">
            <el-input v-model="saveUserForm.age" placeholder="请输入年龄"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="职级">
            <el-select placeholder="请选择"  v-model="saveUserForm.level"
                       @change="loadleader">
              <el-option v-for="level in levelOptions"
                         :label="level.label"
                         :value="level.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="直属领导">
            <el-select placeholder="请选择" v-model="saveUserForm.parentId">
              <el-option  v-for="item in leaderOptions" :label="item.username" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="性别">
            <el-radio-group v-model="saveUserForm.gender">
              <el-radio  value="1" border  style="margin: 0">男</el-radio>
              <el-radio   value="0" border>女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户状态">
            <el-radio-group v-model="saveUserForm.status">
              <el-radio value="1" border  style="margin: 0">启用</el-radio>
              <el-radio value="0" border>禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
<!--      按钮默认是白色-->
      <el-button @click="handleClose">取消</el-button>
      <el-button @click="saveUser" type="primary">启用</el-button>
    </template>
  </el-dialog>

<!--  用户查询卡片-->
  <el-card style="margin: 20px; height: 70px">
<!--
    定义搜索栏时，利用form表单的inline属性，可以让表单内部变成行内元素自动为一行，
    同时，缩小屏幕宽度的时候会自动换行
 -->
    <el-form :inline="true">
        <el-form-item label="用户搜索">
          <el-input placeholder="输入用户名" style="width: 220px;"
                    v-model="searchUserForm.username" @keydown.enter="loadUser" ></el-input>
        </el-form-item>
      <el-form-item label="用户状态" style="width: 290px;">
        <el-select placeholder="请选择用户状态" @change="loadUser"
                   v-model="searchUserForm.status">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadUser">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

<!--  用户信息表格-->
  <el-card style="margin: 20px">
    <el-table :data="userArr">
      <el-table-column type="index" label="编号" width="80px" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" align="center"></el-table-column>
      <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
      <el-table-column prop="createTime" label="用户名" align="center"></el-table-column>
      <el-table-column prop="status" label="用户名" align="center">
        <template #default="scope">
          <el-switch active-value="1" inactive-value="0" v-model="scope.row.status"
                      :disabled="scope.row.level==40"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small"
          @click="resetPassword(scope.row.id)">密码重置</el-button>
          <el-button link type="primary" size="small"
                      @click="editUser(scope.row.id)">编辑</el-button>
          <el-button link type="primary" size="small"
                      @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import {onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";

//控制新增用户弹窗是否显示
const dialogVisible = ref(false);
//定义变量控制dialog的标题
const dialogTitle = ref('新建用户');
// 员工职级
const levelOptions = ref([
    {label:'职员',value:10},
    {label:'经理',value:20},
    {label:'总监',value:30}
]);
// 定义数组保存质数领导数据
const leaderOptions = ref([
  {username:'shaoyun',id:'1'},
  {username:'mike',id:'2'}
])
//根据职级查询可选的质数领导
const loadleader =()=>{
  //优化:如果已经勾选了直属领导，再想重新选择职级的话，需要将之前的直属领导数组和已选择的直属领导数据清空
  leaderOptions.value= [];
  saveUserForm.value.parentId='';
  //获取当前选中的职级,10即为临到的职级
  let level = parseInt(saveUserForm.value.level)+10;
  console.log('level = '+level);
  axios.get(BASE_URL+'/v1/user/select?level='+level).then((response)=>{
    if (response.data.code===2000){
      console.log(response.data.data)
      leaderOptions.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}

// 准备对线用来收集新增/修改员工信息的表单信息
const  saveUserForm = ref({
  username:'',
  phone:'',
  email:'',
  age:'',
  level:'',
  parentId:'',
  gender:'1',
  status:'1',
});
// 新增+更新员工
const saveUser = ()=>{
  let data = qs.stringify(saveUserForm.value)
  axios.post(BASE_URL+'/v1/user/save',data).then((response)=>{
    if (response.data.code===2000){
     ElMessage.success("保存成功")
      dialogVisible.value=false;
      //把表单中的数据清空,标配单恢复到最初始的状态
      saveUserForm.value={};
      loadUser();
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
// 实现取消按钮
const handleClose = ()=>{
  if (confirm('是否关闭本窗口')){
    dialogVisible.value=false;
    //把表单中的数据清空,标配单恢复到最初始的状态
    saveUserForm.value={};
  }
}

//定义数组来保存用户列表的信息
const userArr = ref([]);
//定义对象保存查询条件
const searchUserForm =ref({
  username:'',
  status:''
})
//加载用户功能
const loadUser =()=>{
  //如果传入了查询条件,则根据条件进行查询,没有条件,默认查询所有员工的数据
  let data = qs.stringify(searchUserForm.value);
  axios.get(BASE_URL+'/v1/user/select?'+data).then((response)=>{
    if (response.data.code === 2000){
      ElMessage.success("查询成功")
      userArr.value = response.data.data;
      //清空查询表达的数据
      searchUserForm.value={}
    }else{
      ElMessage.error= response.data.msg;
    }
  })
}
//重置用户搜索数据
const resetSearch =()=>{
  //重置搜索框的数据并且刷新表单的数据
  searchUserForm.value={};
  loadUser();
}
//利用挂载,加载页面的基本信息
onMounted(()=>{
  if (getUser()==null){
    router.push('/login');
  }
  loadUser();//加载员工数据
})

//密码重置
const resetPassword =(userId)=>{
  axios.post(BASE_URL+"/v1/user/update/password/"+userId).then((response)=>{
    if (response.data.code === 2000){
      ElMessage.success('重置成功');
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}

//编辑员工功能
const editUser =(id)=>{
  //修改弹窗标题并且打开弹窗
  dialogTitle.value= '编辑员工';
  dialogVisible.value= true;
  //根据id查询要修改当前员工的信息
  axios.get(BASE_URL+'/v1/user/select?id='+id).then((response)=>{
    if (response.data.code === 2000){
      //如果请求成功就赋值给saveUserForm,因为后端返回的是List.所以这里要写data[0]
      saveUserForm.value =response.data.data[0];
      //准备当前员工直属领导的职级(职级+10)
      let level = parseInt(saveUserForm.value.level)+10;
      //第一次打开编辑窗口也是需要加载当前的职级和可选领导
      axios.get(BASE_URL+'/v1/user/select?level='+level).then((response)=>{
        if (response.data.code === 2000){
          console.log(response.data.data)
          leaderOptions.value=response.data.data;
        }else { //获取领导的接口异常
          ElMessage.error(response.data.msg);
        }
      })
    } else { //查询修改当前员工信息接口异常
      ElMessage.error(response.data.msg)
    }
  })
}

//删除用户
const deleteUser = (userId)=>{
  if (confirm("您确定要删除此用户吗?")){
    axios.post(BASE_URL+'/v1/user/delete/'+userId).then((response)=>{
      if (response.data.code ===2000){
        //消息提示之后并且刷新页面信息
        ElMessage.success("删除用户成功");
        loadUser();
      }else {
        ElMessage.error(response.data.msg);
      }
    })
  }
}
</script>

<style scoped>

</style>